Modeling the Joint Distribution of Wind Speed and Direction using Gaussain Mixture Models

OEN Method: Harris, Cook The parent wind speed distribution: Why Weibull? http://www.sciencedirect.com/science/article/pii/S0167610514001056

Gaussian Mixture Models, http://scikit-learn.org/stable/modules/mixture.html

1. Set up

1.1 Environment

In [1]:
%matplotlib inline
%load_ext autoreload
%autoreload 2

from import_file import *
from helpers.parallel_helper import *
load_libs()

plt.rcParams['axes.autolimit_mode'] = 'round_numbers'
plt.rcParams['axes.xmargin'] = 0.
plt.rcParams['axes.ymargin'] = 0.
mpl.rcParams['patch.force_edgecolor'] = True

1.2 Read Data

In [2]:
# file_path, bandwidth= './data/NCDC/europe/uk/marham/dat.txt', 1.7
# file_path, bandwidth, NUMBER_OF_GAUSSIAN= './data/NCDC/europe/uk/tiree/dat.txt', 1.9, 4 
# file_path, bandwidth, NUMBER_OF_GAUSSIAN = './data/NCDC/europe/uk/boscombe_down/dat.txt', 1.5, 4
# file_path, bandwidth= './data/NCDC/europe/uk/middle_wallop/dat.txt', 1.3
# file_path, bandwidth= './data/NCDC/europe/uk/bournemouth/dat.txt',1.3 # 4?
# file_path= "./data/NCDC/europe/uk/weybourne/dat.txt"
# file_path= "./data/NCDC/europe/uk/skye_lusa/dat.txt" # 
# file_path= "./data/NCDC/europe/uk/wattisham/dat.txt"
# file_path= "./data/NCDC/europe/uk/south_uist_range/dat.txt" # inpropoer direction R square measure
# file_path= "./data/NCDC/europe/uk/holbeach/dat.txt" # inpropoer direction R square measure
# file_path= "./data/NCDC/europe/uk/cambridge/dat.txt" # inpropoer direction R square measure
# file_path= "./data/NCDC/europe/us/baltimore/dat.txt" # time too short
# file_path= "./data/NCDC/europe/uk/bealach_na_ba/dat.txt" # time too short
# file_path= "./data/NCDC/europe/uk/benbecula/dat.txt" # truncate (untruncate in m/s), 4?
# file_path= './data/NCDC/europe/uk/southhamption/dat.txt' # high 0, trend

# file_path, bandwidth, NUMBER_OF_GAUSSIAN = "./data/NCDC/europe/germany/landsberg_lech/dat.txt", 0.9, 4 
# file_path, bandwidth= "./data/NCDC/europe/germany/neuburg/dat.txt", 0.7
# file_path, bandwidth= "./data/NCDC/europe/germany/laupheim/dat.txt", 0.7 # double peak, 4?, trend
# file_path, bandwidth= "./data/NCDC/europe/germany/holzdorf/dat.txt", 0.9 # 2008 year
# file_path, bandwidth, NUMBER_OF_GAUSSIAN= './data/NCDC/europe/france/nantes/dat.txt', 0.9, 4 # unit shift, one direction deviate big
# file_path= './data/NCDC/europe/france/pau_pyrenees/dat.txt' # unit shift, 2; force using knot 
# file_path= "./data/NCDC/europe/france/avord/dat.txt" # try 4, initial speed (should be good with m/s), incompete dataset
# file_path= "./data/NCDC/europe/france/vatry/dat.txt"  # double peak, initial speed, incompete dataset
# file_path, bandwidth, NUMBER_OF_GAUSSIAN= "./data/NCDC/europe/spain/valladolid/dat.txt", 1.1, 4
# file_path= './data/NCDC/europe/spain/jerez/dat.txt' # high 0
# file_path, bandwidth= "./data/NCDC/europe/spain/barayas/dat.txt", 0.7 # not good fit
# file_path, bandwidth= './data/NCDC/europe/spain/malaga/dat.txt', 0.7 # directions blocked?
# file_path, bandwidth= './data/NCDC/europe/spain/tenerife_sur/dat.txt', 0.7 # directions blocked?
# file_path, bandwidth= './data/NCDC/europe/spain/almeria/dat.txt', 0.7 # negative dimensions?
# file_path, bandwidth= './data/NCDC/europe/greece/eleftherios_intl/dat.txt',0.7 # some direction might be blocked
# file_path= './data/NCDC/europe/ciampino/dat.txt' # try 4, bandwidth?
# file_path= "./data/NCDC/europe/huspel_aws/dat.txt"  # integer, 4?
# file_path= './data/NCDC/gibraltar/dat.txt' # bad fit

# MidEast
# file_path, bandwidth= './data/NCDC/mideast/uae/al_maktoum/dat.txt', 1.1
# file_path= './data/NCDC/mideast/uae/sharjah_intl/dat.txt' 
# file_path= './data/NCDC/mideast/uae/dubai_intl/dat.txt' 
# file_path= './data/NCDC/mideast/uae/abu_dhabi_intl/dat.txt' # Time shift
# file_path= './data/NCDC/mideast/uae/bateen/dat.txt' # Time shift
# file_path= './data/NCDC/mideast/buraimi/dat.txt' # not good dataset
# file_path= './data/NCDC/mideast/turkey/konya/dat.txt' 
# file_path= './data/NCDC/mideast/turkey/sivas/dat.txt' # bad dataset
# file_path= './data/NCDC/mideast/turkey/balikesir/dat.txt' # bad dataset
# file_path= './data/NCDC/mideast/turkey/bartin/dat.txt' # bad dataset
# file_path= './data/NCDC/mideast/iran/chahbahar/dat.txt'
# file_path= './data/NCDC/mideast/iran/zabol/dat.txt' # Problematic data
# file_path= './data/NCDC/mideast/iran/torbat_heydarieh/dat.txt' # Unusable

file_path, bandwidth = "./data/NCDC/cn/shanghai/hongqiao_intl/dat.txt", 0.6
# file_path, bandwidth= "./data/NCDC/cn/shanghai/pudong/dat.txt", 0.8
# file_path, bandwidth= "./data/NCDC/cn/hefei_luogang/dat.txt", 0.6 # few 0, trend, try 2
# file_path, bandwidth= "./data/NCDC/cn/nanjing_lukou/dat.txt", 0.5
# file_path= "./data/NCDC/cn/zhengzhou_xinzheng/dat.txt" 
# file_path= "./data/NCDC/cn/tianjin/binhai/dat.txt" # few 0, trend, stationary speed, unstationary direction
# file_path= "./data/NCDC/cn/tianjin/tianjing/dat.txt" # 16 sectors
# file_path= "./data/NCDC/cn/shijiazhuang_zhengding/dat.txt" 
# file_path= "./data/NCDC/cn/henan_gushi/dat.txt" # 16 sectors, fit not very good
# file_path= "./data/NCDC/cn/nanning_wuxu/dat.txt" # numpy priblem, unstationary speed
# file_path= './data/NCDC/cn/macau/dat.txt'  
# file_path= "./data/NCDC/cn/hk_intl/dat.txt" # few 0

# file_path= './data/NCDC/southeast_asia/malaysia/mersing/dat.txt' # 2 mode, paper comparison
# file_path= './data/NCDC/southeast_asia/malaysia/penang/dat.txt'
# file_path= './data/NCDC/southeast_asia/malaysia/butterworth/dat.txt' # 2 mode 
# file_path= "./data/NCDC/southeast_asia/malaysia/bsultan_mahmud/dat.txt" # stable
# file_path= "./data/NCDC/southeast_asia/malaysia/bsultan_ismail/dat.txt" # 
# file_path= "./data/NCDC/southeast_asia/singapore/changi/dat.txt" # trend, no 0, questionary data
# file_path= "./data/NCDC/southeast_asia/singapore/paya_lebar/dat.txt" # questionary data
# file_path= "./data/NCDC/southeast_asia/singapore/seletar/dat.txt"
# file_path= "./data/NCDC/east_asia/cheongju_intl/dat.txt" # 2005-2009  may have problem, fit is good; numpy problem
# file_path= "./data/NCDC/east_asia/daegu_ab/dat.txt" # recent 5 year may have problem, but fit is generally good; numpy problem

# file_path, bandwidth= "./data/NCDC/oceania/auckland_intl/dat.txt", 0.9  # Good data, double mode
# file_path= "./data/NCDC/oceania/brisbane_archerfield/dat.txt" # high 0, few data 
# file_path= "./data/NCDC/oceania/narrandera/dat.txt" # high 0, few data
# file_path, bandwidth= "./data/NCDC/oceania/canberra/dat.txt", 0.7 # high 0, bad fit

# file_path, bandwidth= './data/NCDC/us/boston_16nm/dat.txt', 0.9 # Offshore, mixed type

# file_path, bandwidth, NUMBER_OF_GAUSSIAN  = './data/asos/bismarck_ND/hr_avg.csv', 1.1, 4
# file_path, bandwidth, NUMBER_OF_GAUSSIAN = './data/asos/aberdeen_SD/hr_avg.csv', 1.7, 2 # only to 2012
# file_path, bandwidth, NUMBER_OF_GAUSSIAN = './data/asos/minneapolis/hr_avg.csv', 1.1, 4
# file_path, bandwidth = './data/asos/lincoln_NE/hr_avg.csv', 0.9
# file_path, bandwidth = './data/asos/des_moines_IA/hr_avg.csv', 1.3
# file_path, bandwidth = './data/asos/springfield_IL/hr_avg.csv', 1.1 
# file_path, bandwidth = './data/asos/topeka/hr_avg.csv', 0.7 # High 0
# file_path, bandwidth = './data/asos/denver/hr_avg.csv', 1.3

# file_path, bandwidth, NUMBER_OF_GAUSSIAN = './data/NDAWN/baker/hr_avg.csv', 0.7, 4 
# file_path, bandwidth = './data/NDAWN/dickinson/hr_avg.csv', 0.6
# file_path = './data/NDAWN/rugby/hr_avg.csv'
# file_path = './data/NDAWN/bowman/hr_avg.csv'
# file_path = './data/NDAWN/grand_forks/hr_avg.csv'
# file_path = './data/NDAWN/williston/hr_avg.csv'
# file_path = './data/NDAWN/jamestown/hr_avg.csv'
In [3]:
if "cn_database" in file_path: 
    df = read_cn_database(file_path)
elif 'NCDC' in file_path:
    df = pd.read_csv(file_path, header=0, skipinitialspace=True, dtype={'HrMn':'object'})
    df.rename(columns={'Date':'date','Dir':'dir','Spd':'speed','Type':'type','I.1':'wind_type'}, inplace=True)
    df = df[['date','HrMn','type','dir','speed','wind_type' ]]
    df.dropna(subset=['dir','speed'], inplace=True)
    integer_data = True
elif 'NDAWN' in file_path:
    df = pd.read_csv(file_path, header=0, skipinitialspace=True, dtype={'HrMn':'object'})
    df['type']='default'
    df['wind_type']='default'
    df = df.dropna()
    integer_data = False
    knot_unit = False
else:
    # ASOS
    df = pd.read_csv(file_path, header=0, skipinitialspace=True, dtype={'HrMn':'object'})
    df['type']='default'
    df['wind_type']='default'
    df = df.dropna()
    integer_data = False
    knot_unit = True
In [4]:
df
Out[4]:
date HrMn type dir speed wind_type
0 19560820 0000 FM-12 200 5.1 N
1 19560820 0300 FM-12 250 4.1 N
2 19560820 0600 FM-12 250 5.1 N
3 19560820 0900 FM-12 270 6.2 N
4 19560820 1200 FM-12 270 5.1 N
5 19560820 1800 FM-12 290 3.1 N
6 19560820 2100 FM-12 320 3.1 N
7 19560821 0000 FM-12 320 3.1 N
8 19560821 0300 FM-12 290 4.1 N
9 19560821 0600 FM-12 270 5.1 N
10 19560821 0900 FM-12 320 2.1 N
11 19560821 1200 FM-12 90 1.0 N
12 19560821 1800 FM-12 140 2.1 N
13 19560821 2100 FM-12 140 2.1 N
14 19560822 0300 FM-12 140 6.2 N
15 19560822 0600 FM-12 160 4.1 N
16 19560822 1200 FM-12 140 4.1 N
17 19560822 1800 FM-12 200 3.1 N
18 19560822 2100 FM-12 290 7.2 N
19 19560823 0300 FM-12 270 7.2 N
20 19560823 0900 FM-12 320 5.1 N
21 19560823 1200 FM-12 270 1.0 N
22 19560823 2100 FM-12 999 0.0 C
23 19560824 0000 FM-12 999 0.0 C
24 19560824 0300 FM-12 270 1.0 N
25 19560824 0600 FM-12 90 1.0 N
26 19560824 0900 FM-12 160 2.1 N
27 19560824 1200 FM-12 999 0.0 C
28 19560824 1800 FM-12 999 0.0 C
29 19560824 2100 FM-12 140 4.1 N
... ... ... ... ... ... ...
359333 20150301 0900 FM-15 270 4.0 N
359334 20150301 0930 FM-15 260 4.0 V
359335 20150301 1000 FM-15 250 4.0 V
359336 20150301 1030 FM-15 250 3.0 V
359337 20150301 1100 FM-15 260 4.0 N
359338 20150301 1130 FM-15 230 3.0 N
359339 20150301 1200 FM-15 230 2.0 V
359340 20150301 1230 FM-15 270 3.0 N
359341 20150301 1300 FM-15 240 2.0 V
359342 20150301 1330 FM-15 260 2.0 V
359343 20150301 1400 FM-15 250 2.0 V
359344 20150301 1430 FM-15 240 2.0 V
359345 20150301 1500 FM-15 999 0.0 C
359346 20150301 1530 FM-15 999 1.0 V
359347 20150301 1600 FM-15 999 1.0 V
359348 20150301 1630 FM-15 210 1.0 N
359349 20150301 1700 FM-15 999 1.0 V
359350 20150301 1730 FM-15 999 1.0 V
359351 20150301 1800 FM-15 999 1.0 V
359352 20150301 1830 FM-15 180 1.0 N
359353 20150301 1900 FM-15 160 1.0 N
359354 20150301 1930 FM-15 210 1.0 N
359355 20150301 2000 FM-15 230 2.0 N
359356 20150301 2030 FM-15 230 1.0 N
359357 20150301 2100 FM-15 240 2.0 N
359358 20150301 2130 FM-15 180 1.0 N
359359 20150301 2200 FM-15 160 1.0 N
359360 20150301 2230 FM-15 150 1.0 N
359361 20150301 2300 FM-15 190 2.0 N
359362 20150301 2330 FM-15 190 1.0 N

359363 rows × 6 columns

In [5]:
if 'NCDC' in file_path:
    lat, long = get_lat_long(file_path)
    print(lat,long)
    map_osm = folium.Map(location=[lat, long], zoom_start=4)
    folium.Marker([lat, long]).add_to(map_osm)
    display(map_osm)
31.198 121.336
In [6]:
df['time']=pd.to_datetime(df["date"].astype(str).map(str) + df["HrMn"], format='%Y%m%d%H%M')
df.set_index(['time'], inplace=True)
df['HrMn']=df['HrMn'].astype(int)
df = df.query("(dir <= 999) & (speed < 100) & \
              (date >= 19700000) & (date < 20170000) ")
In [7]:
plot_speed_and_angle_distribution(df.speed, df.dir)
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
In [8]:
# Dir [10,360]=> [0,350]
df['dir'] = df['dir'].apply(lambda x: x%360 if x < 999 else x) 
df['month'] = df['date']%10000//100
# Convert Windrose coordianates to Polar Cooridinates 
df['dir_windrose'] = df['dir']
df['dir'] = df['dir'].apply(lambda x: (90 - x)%360 if x < 999 else x)
display(df.describe())
df.plot(y='speed',legend=True,figsize=(20,5))
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:2: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  from ipykernel import kernelapp as app
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:3: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  app.launch_new_instance()
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:5: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:6: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
date HrMn dir speed month dir_windrose
count 3.369710e+05 336971.000000 336971.000000 336971.000000 336971.000000 336971.000000
mean 2.000006e+07 1128.070137 268.228497 3.543890 6.536892 248.807883
std 1.115119e+05 691.735348 275.924866 2.002307 3.448796 279.529540
min 1.973010e+07 0.000000 0.000000 0.000000 1.000000 0.000000
25% 1.991120e+07 530.000000 90.000000 2.000000 4.000000 90.000000
50% 2.002062e+07 1100.000000 200.000000 3.000000 7.000000 150.000000
75% 2.010050e+07 1730.000000 320.000000 5.000000 10.000000 310.000000
max 2.015030e+07 2357.000000 999.000000 30.000000 12.000000 999.000000
Out[8]:
<matplotlib.axes._subplots.AxesSubplot at 0xcd62550>

1.3 General Data Info

1.3.1 Unit Detection

In [9]:
df['decimal'] = df.speed % 1
df.decimal.hist(alpha=0.5, label='m/s', figsize=(4, 3))
if 'knot_unit' not in globals():
    knot_unit = True if len(df.query('decimal >= 0.2')) / len(df) > 0.3 else False
    if knot_unit:
        df['speed'] = df['speed'] * 1.943845
        df['decimal'] = df.speed % 1
        df.decimal.hist(alpha=0.5, label='knot')
        # need more elaboration, some is not near an integer
        df['speed'] = df['speed'].apply(lambda x: int(round(x)))
    plt_configure(xlabel='Decimal', ylabel='Frequency', legend={'loc': 'best'}, title='Decimal Distribution')
    
df.drop(['decimal'], 1,inplace=True)
print(knot_unit)
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  if __name__ == '__main__':
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:13: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
False
In [10]:
dir_unit_text = ' (degree)'
if knot_unit == True:
    speed_unit_text = ' (knot)'
else: 
    speed_unit_text = ' (m/s)'

1.3.2 Sampling Type Selection

In [11]:
sample_type = df.query('date > 20000000')['type']
sample_type.value_counts().plot(
    kind = 'bar', title = 'Report Types Comprisement', figsize=(4,3))

report_type_most_used = sample_type.value_counts().argmax()
df = df.query("type==@report_type_most_used")

1.3.3 Sampling Time Selection

In [12]:
MID_YEAR = (min(df.date)//10000+max(df.date)//10000)//2

df['HrMn'].value_counts().sort_index().plot(kind='bar', alpha=0.5,label='Overall')
df.query('date > @MID_YEAR * 10000')['HrMn'].value_counts().sort_index().plot(
    kind='bar', alpha=0.5, label='> %s' %  MID_YEAR )

plt_configure(xlabel='Sampling Time', ylabel='Frequency', legend={'loc':'best'}, figsize=(8, 4), 
              title = 'Sampling Time Distribution, Overall and > %s ' %  MID_YEAR)
In [13]:
df['sample_time'] = df.HrMn % 100 
sample_time = df.query('date > 20000000')['sample_time']
sample_times = sample_time.value_counts()[sample_time.value_counts() > 2000]
sample_times = sample_times.index.tolist()
# df = df.query("sample_time in @sample_times")
df = df.query("sample_time == @sample_times[0]")
df.drop(['sample_time'], 1,inplace=True)
print(sample_times)

df['HrMn'].value_counts().sort_index().plot(kind='bar', alpha=0.5, figsize=(10, 4))
[0, 30]
Out[13]:
<matplotlib.axes._subplots.AxesSubplot at 0xd937c88>

1.4 Error Data handling and Adjustment

1.4.1 Artefacts

wrong direction record

In [14]:
if integer_data:
    display(df.query("(dir % 10 >= 0.1) & (dir != 999)"))
    df = df.query('(dir % 10 <= 0.1) | (dir == 999)')
date HrMn type dir speed wind_type month dir_windrose
time
1994-01-28 00:00:00 19940128 0 FM-15 119 3.0 N 1 331
1994-07-18 10:00:00 19940718 1000 FM-15 337 5.0 N 7 113
1994-08-05 11:00:00 19940805 1100 FM-15 335 9.0 N 8 115
1994-08-10 05:00:00 19940810 500 FM-15 319 10.0 N 8 131
1994-09-03 21:00:00 19940903 2100 FM-15 331 5.0 N 9 119
1994-12-03 14:00:00 19941203 1400 FM-15 316 3.0 N 12 134
1995-04-03 13:00:00 19950403 1300 FM-15 337 3.0 N 4 113
1998-06-03 11:00:00 19980603 1100 FM-15 59 10.0 N 6 31
1998-09-09 12:00:00 19980909 1200 FM-15 359 20.0 N 9 91

sudden increase in speed

In [15]:
# sudden increse
df['incre'] = df.speed.diff(1)
df['incre'].fillna(0, inplace=True)
df['incre_reverse'] = df.speed.diff(-1)
df['incre_reverse'].fillna(0, inplace=True)

display(df.sort_values(by='speed',ascending=False).head(10))
df['incre'].plot(kind='hist', bins=arange(-15, 15), legend=True, figsize=(8, 3))
date HrMn type dir speed wind_type month dir_windrose incre incre_reverse
time
1993-12-21 22:00:00 19931221 2200 FM-15 110 22.0 N 12 340 19.0 20.0
1993-08-02 14:00:00 19930802 1400 FM-15 140 21.0 N 8 310 17.0 21.0
1985-04-30 08:00:00 19850430 800 FM-15 310 16.0 N 4 140 9.8 9.8
2005-09-11 17:00:00 20050911 1700 FM-15 0 16.0 N 9 90 4.0 4.0
1981-12-19 07:00:00 19811219 700 FM-15 140 15.9 N 12 310 13.9 3.1
1994-10-20 08:00:00 19941020 800 FM-15 140 15.0 N 10 310 6.0 8.0
2012-08-08 05:00:00 20120808 500 FM-15 10 15.0 N 8 80 0.0 2.0
1995-11-07 04:00:00 19951107 400 FM-15 110 15.0 N 11 340 5.0 2.0
2012-08-08 04:00:00 20120808 400 FM-15 0 15.0 N 8 90 2.0 0.0
2008-07-02 08:00:00 20080702 800 FM-15 170 15.0 N 7 280 10.0 13.0
Out[15]:
<matplotlib.axes._subplots.AxesSubplot at 0xce82e48>
In [16]:
incre_threshold = 20 if knot_unit else 10
print('sudden increase number', len(df.query('(incre > @incre_threshold )&(incre_reverse > @incre_threshold )')))
df = df.query('(incre < @incre_threshold )|(incre_reverse < @incre_threshold )')

# Check the max speed
display(df.sort_values(by='speed',ascending=False).head(10))
df.drop(['incre', 'incre_reverse'], 1, inplace=True)
sudden increase number 2
date HrMn type dir speed wind_type month dir_windrose incre incre_reverse
time
2005-09-11 17:00:00 20050911 1700 FM-15 0 16.0 N 9 90 4.0 4.0
1985-04-30 08:00:00 19850430 800 FM-15 310 16.0 N 4 140 9.8 9.8
1981-12-19 07:00:00 19811219 700 FM-15 140 15.9 N 12 310 13.9 3.1
2012-08-08 04:00:00 20120808 400 FM-15 0 15.0 N 8 90 2.0 0.0
2012-08-08 05:00:00 20120808 500 FM-15 10 15.0 N 8 80 0.0 2.0
1995-11-07 04:00:00 19951107 400 FM-15 110 15.0 N 11 340 5.0 2.0
1995-03-09 15:00:00 19950309 1500 FM-15 110 15.0 N 3 340 4.0 3.0
1994-10-20 08:00:00 19941020 800 FM-15 140 15.0 N 10 310 6.0 8.0
2013-03-09 17:00:00 20130309 1700 FM-15 80 14.0 N 3 10 8.0 2.0
2005-08-06 03:00:00 20050806 300 FM-15 350 14.0 N 8 100 4.0 1.0

1.4.2 Direction re-aligment

For some dataset, the 16 sectors are not record properly,

e.g. the sectors are [0,20,50 ...], need to redistribute the angle into 22.5, e.g. [0, 22.5, 45...]

In [17]:
display(df['dir'].value_counts().sort_index())
effective_column = df.query('dir < 999')['dir'].value_counts()[df['dir'].value_counts() > 30].sort_index()
if integer_data:
    SECTOR_LENGTH = 360/len(effective_column) 
else: 
    SECTOR_LENGTH = 10
print(len(effective_column), SECTOR_LENGTH)
0       5114
10      3736
20      3931
30      4370
40      4484
50      6036
60      6681
70      5524
80      5811
90      8968
100     8340
110     7085
120     7931
130     6770
140     4428
150     3796
160     3319
170     2573
180     2191
190     1555
200     1578
210     1991
220     1885
230     1882
240     2132
250     2360
260     3096
270     4399
280     4881
290     7184
300    11033
310     9313
320     9832
330    10032
340     7915
350     6258
999    25824
Name: dir, dtype: int64
36 10.0
In [18]:
df=realign_direction(df, effective_column)

1.4.3 0 Speed

In [19]:
with_too_many_zero, null_wind_frequency = is_with_too_many_zero(df.query("(date >= 20050000)"))
delete_zero = with_too_many_zero
if delete_zero:
    df = df.query('(speed > 0)')
print(delete_zero, null_wind_frequency)
False 0.0412621359223
In [20]:
print(df.query('dir == 999')['speed'].value_counts())
df=fill_direction_999(df, SECTOR_LENGTH)
0.0    15499
2.0     5486
1.0     4531
3.0      229
4.0       43
5.0       15
3.1        8
4.1        4
2.1        3
7.0        2
5.1        2
6.0        2
Name: speed, dtype: int64

1.5 Time Shift Comparison

In [21]:
DIR_REDISTRIBUTE = 'even'
if DIR_REDISTRIBUTE == 'even':
    DIR_BIN = arange(-5, 360, 10) 
elif DIR_REDISTRIBUTE == 'round_up':
    DIR_BIN = arange(0, 360+10, 10) 

# Comparison between mid_year, looking for: 
# 1. Odd Even Bias
# 2. Time Shift of Wind Speed Distribution
bins = arange(0, df.speed.max() + 1)
df.query('date < @MID_YEAR * 10000')['speed'].plot(
    kind='hist', alpha=0.5,bins=bins, label='< %s' % MID_YEAR)

df.query('date > @MID_YEAR * 10000')['speed'].plot(
    kind='hist', alpha=0.5,bins=bins, label='> %s' % MID_YEAR)

plt.suptitle('Speed Comparison between year < %s, > %s ' % (MID_YEAR, MID_YEAR), fontsize = 14)
plt_configure(xlabel='Speed', ylabel='Frequency', legend=True, figsize=(8, 3))
In [22]:
df.query('date < @MID_YEAR * 10000')['dir'].plot(
    kind='hist', alpha=0.5,bins=DIR_BIN, label='< %s' % MID_YEAR)

df.query('date > @MID_YEAR * 10000')['dir'].plot(
    kind='hist', alpha=0.5,bins=DIR_BIN, label='> %s' % MID_YEAR)

plt.suptitle('Dir Comparison between year < %s, and > %s ' % (MID_YEAR, MID_YEAR), fontsize = 14)
plt_configure(xlabel='Dir', ylabel='Frequency', legend={'loc':'best'}, figsize=(8, 3), tight='x')
In [23]:
display(df[df['dir'].isnull()])
df.dropna(subset=['dir'], inplace=True)
date HrMn type dir speed wind_type month dir_windrose
time
In [24]:
# Inspect the time shift of speed and degree distribution, and odd-even bias
check_time_shift(df, speed_unit_text=speed_unit_text, dir_unit_text=dir_unit_text)
1979 - 1979
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
1980 - 1984
1985 - 1989
1990 - 1994
1995 - 1999
2000 - 2004
2005 - 2009
2010 - 2014
2015 - 2015
In [25]:
df.resample('A').mean().plot(y='speed')
plt.gca().set_ylim(bottom=0)
df.resample('M').mean().plot(y='speed', figsize=(20,4))
plt.gca().set_ylim(bottom=0)
Out[25]:
(0, 6.0)
In [26]:
for column in ['speed', 'dir']:
    if column == 'speed':
        bins = arange(0, df[column].max()+1, 1)
    else:
        bins = arange(0, 361, 10)
    den, _ = np.histogram(df[column], bins=bins, density=True)
    y_top=max(den)*1.2
    for year in arange(1980, 2016):
        end_year = year
        sub_df = df[str(year):str(end_year)]
        if len(sub_df) > 5000:
            plt.figure()
            df[column].hist(bins=bins, alpha=0.3, normed=True)
            sub_df[column].hist(bins=bins, alpha=0.5, figsize=(3,1.5), normed=True)
            plt.gca().set_ylim(top=y_top)
            plt_configure(title=str(year))
    align_figures()
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py:524: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
  max_open_warning, RuntimeWarning)
In [27]:
for column in ['speed', 'dir']:
    if column == 'speed':
        bins = arange(0, df[column].max()+1, 1)
    else:
        bins = arange(0, 361, 10)
    density_all, _ = np.histogram(df[column], bins=bins, density=True)
    df[column].hist(bins=bins, figsize=(5,3))

    R_squares = []
    years = []
    for year in arange(1980, 2016):
        start_year, end_year = year-1, year+1
        sub_df = df[str(start_year):str(end_year)]
        if len(sub_df) > 5000:
            density, _ = np.histogram(sub_df[column], bins=bins, density=True)
            y_mean = np.mean(density_all)
            SS_tot = np.sum(np.power(density_all - y_mean, 2))
            SS_res = np.sum(np.power(density_all - density, 2))

            R_square = 1 - SS_res / SS_tot
            R_squares.append(R_square)
            years.append(year)

    plt.figure()
    plot(years, R_squares)
    ylim = max(min(plt.gca().get_ylim()[0],0.85),0)
    plt.gca().set_ylim(bottom=ylim, top=1)
    plt_configure(figsize=(5,3))
    align_figures()

1.6 Re-distribute Direction and Speed (Optional)

e.g. Dir 50 -> -45 ~ 55, to make KDE result better

In [28]:
if integer_data:
    df = randomize_angle(df, DIR_REDISTRIBUTE, SECTOR_LENGTH)
In [29]:
if integer_data:
    if delete_zero:
        redistribute_method = 'down'
    else:
        redistribute_method = 'up'

    df, speed_redistribution_info = randomize_speed(df, redistribute_method)
Redistribute upward, e.g. 0 -> [0,1]

1.7 Generate (x,y) from (speed,dir)

In [30]:
# Cook orientation
# df['dir']= (df['dir'] + 180)%360
In [31]:
# There might be a small dot in the centre, which is due to too many zero (more than 1 speed) in center
# Scatter plot in matplot has performance issue, the speed is very slow
df['x'] = df['speed'] * cos(df['dir'] * pi / 180.0)
df['y'] = df['speed'] * sin(df['dir'] * pi / 180.0)

2. Re-select Data and Overview

2.1 Data Overview

In [32]:
## Summery of the data selection
print('Knot unit?', knot_unit)
print('Report type used:', report_type_most_used)
print('Sampling time used:', sample_times)
if 'speed_redistribution_info' in globals():
    print('Speed redistribution info:', speed_redistribution_info )

df_all_years = df # for later across-year comparison
df = df_all_years.query('(date >= 20100000) & (date < 20150000)')
# df = df.query('(HrMn == 0) and (speed >= 0.5) and (date%10000 > 900) and (date%10000 < 1000)' )
df.describe()
Knot unit? False
Report type used: FM-15
Sampling time used: [0, 30]
Speed redistribution info: Redistribute upward, e.g. 0 -> [0,1]
Out[32]:
date HrMn dir speed month dir_windrose x y
count 4.364500e+04 43645.000000 43645.000000 43645.000000 43645.000000 43645.000000 43645.000000 43645.000000
mean 2.012065e+07 1149.361897 184.828196 4.509910 6.525398 212.598350 1.026380 0.397005
std 1.413268e+04 692.143261 114.244256 1.983946 3.450254 239.640963 3.021522 3.732975
min 2.010010e+07 0.000000 -4.994104 0.000587 1.000000 0.000000 -12.543796 -11.048801
25% 2.011040e+07 500.000000 84.951225 3.138135 4.000000 80.000000 -0.921013 -2.423456
50% 2.012070e+07 1100.000000 167.533890 4.375099 7.000000 140.000000 1.374458 0.076315
75% 2.013093e+07 1700.000000 302.587933 5.743895 10.000000 280.000000 3.304786 3.337204
max 2.014123e+07 2300.000000 354.999458 15.743165 12.000000 999.000000 15.598125 13.699125
In [33]:
df.plot(y='speed',legend=True,figsize=(20,5))
Out[33]:
<matplotlib.axes._subplots.AxesSubplot at 0x1b81c5c0>
In [34]:
# Accumulation by month
df.resample('M').count().plot(y='date', kind='bar',figsize=(20,4))
Out[34]:
<matplotlib.axes._subplots.AxesSubplot at 0x1b32ea58>
In [35]:
# 90 degree is east
ax = WindroseAxes.from_ax()
viridis = plt.get_cmap('viridis')
ax.bar(df.dir_windrose, df.speed, normed=True, opening=0.8, edgecolor='white', nsector=36, cmap=viridis)
ax.set_legend()
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\cbook.py:136: MatplotlibDeprecationWarning: The axisbg attribute was deprecated in version 2.0. Use facecolor instead.
  warnings.warn(message, mplDeprecation, stacklevel=1)
In [36]:
if len(df) > 1000000:
    bins=arange(0,362)
    df['dir'].hist(bins=bins, normed=True,alpha=0.5,label='min')
    
    df = df_all_years.sample(n=500000, replace=True)    
    df['dir'].hist(bins=bins, normed=True,alpha=0.5,label='min resmapled')
    plt_configure(legend=True, figsize=(20,4))
In [37]:
x, y_weibull, y_cdf_weibull, weibull_params, y_ecdf = fit_weibull_and_ecdf(df.speed)

# 1. Histogram comparison
fig = plt.figure()
df['speed'].hist(bins=arange(0, df.speed.max()), alpha=0.5, label='Data', normed=True)             
plot(x, y_weibull, '-', color='black',label='Weibull')   
plt_configure(figsize=(4,3),xlabel='V',ylabel='PDF', legend=True)

# 2. CDF comparison
fig = plt.figure()
plot(log(x), log(-log(1-y_ecdf)),'o', label='ECDF')
plot(log(x), log(-log(1-y_cdf_weibull)),'-', label='Weibull')
plt_configure(xlabel="ln(V)", ylabel="ln(-ln(1-P)",legend={'loc':'best'}, figsize=(4,3))
align_figures()
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:11: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:12: RuntimeWarning: divide by zero encountered in log
In [38]:
df.plot(kind='scatter', x='x', y='y', alpha=0.05, s=2)
plt.gca().set_aspect('equal')
plt_configure(figsize=(3.2,3.2),xlabel='x'+speed_unit_text, ylabel='y'+speed_unit_text)

2.2 Overview by Direction

In [39]:
if len(effective_column) == 16:
    rebinned_angle = 22.5
else: 
    rebinned_angle = 10
In [40]:
%%time
original_incre, incre = SECTOR_LENGTH, rebinned_angle
start, end = -original_incre/2 + incre/2, 360

max_speed = df.speed.max()
max_count = max_count_for_angles(df, start, end, incre)
plot_range = [0, max_speed, 0, max_count*1.05]

for angle in arange(start, end, incre):
    start_angle, end_angle = angle-incre/2, angle+incre/2
    sub_df, sub_max_speed = select_df_by_angle(df, start_angle, end_angle)   
    
    fig = plt.figure()
    sub_df['speed'].hist(bins=arange(0, max_speed), alpha=0.5, label='Data')
    title ='%s (%s - %s), %s' % (angle, start_angle, end_angle, len(sub_df)) 
    plt.axis(plot_range)
    plt_configure(figsize=(3,1.5), title=title)
align_figures()
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py:524: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
  max_open_warning, RuntimeWarning)
Wall time: 6.43 s

2.3 Overview by Month

In [41]:
%%time
month_incre = 1
current_df = df.query('speed>=1')
for month in arange(1, 12+month_incre, month_incre): 
    end_month = month+month_incre
    sub_df = current_df.query('(month >= @month) and (month < @end_month)')
    if len(sub_df) > 0:
        title = 'Month: %s' % (month)
        ax = WindroseAxes.from_ax()
        ax.bar(sub_df.dir_windrose, sub_df.speed, normed=True, opening=0.8, edgecolor='white', nsector=36, cmap=plt.get_cmap('viridis'))
        plt_configure(figsize=(3,3), title=title)
align_figures()
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\cbook.py:136: MatplotlibDeprecationWarning: The axisbg attribute was deprecated in version 2.0. Use facecolor instead.
  warnings.warn(message, mplDeprecation, stacklevel=1)
Wall time: 19 s

3. Create input data and configuration

In [42]:
SPEED_SET = array(list(zip(df.x, df.y)))
if 'NUMBER_OF_GAUSSIAN' not in globals():
    NUMBER_OF_GAUSSIAN = 3
FIT_METHOD = 'square_error'
DEFAULT_BANDWDITH = 1.5 if knot_unit else 0.7
fig_list = []
In [43]:
fit_limit = ceil(df['speed'].quantile(.95))
fitting_axis_range = arange(-fit_limit, fit_limit+1, 1)
print(fitting_axis_range)

FITTING_RANGE = []
for i in fitting_axis_range:
    for j in fitting_axis_range:
        FITTING_RANGE.append([i,j])
[-8 -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7  8]
In [44]:
plot_limit = ceil(df['speed'].quantile(.95))
PLOT_AXIS_RANGE = arange(-plot_limit, plot_limit+1, 1)

4. Kernel Density Estimation

In [45]:
sample = SPEED_SET
KDE_KERNEL = 'gaussian'
# KDE_KERNEL, bandwidth = 'tophat', 1
In [46]:
%%time
if 'bandwidth' not in globals():
    bandwidth = DEFAULT_BANDWDITH
    from sklearn.grid_search import GridSearchCV
    # from sklearn.model_selection import GridSearchCV  ## too slow

    # The bandwidth value sometimes would be too radical
    if knot_unit:
        bandwidth_range = arange(0.7,2,0.2)
    else:
        bandwidth_range = arange(0.4,1,0.1)

    # Grid search is unable to deal with too many data (a long time is needed)
    if len(sample) > 50000:    
        df_resample=df.sample(n=50000, replace=True)
        bandwidth_search_sample = array(list(zip(df_resample.x, df_resample.y)))
    else:
        bandwidth_search_sample = sample

    grid = GridSearchCV(neighbors.KernelDensity(kernel = KDE_KERNEL),
                    {'bandwidth': bandwidth_range}, n_jobs=-1, cv=4) 

    grid.fit(bandwidth_search_sample)
    bandwidth = grid.best_params_['bandwidth']
    
print(bandwidth)
0.6
Wall time: 0 ns
In [47]:
if 'bandwidth' not in globals():
    bandwidth = DEFAULT_BANDWDITH

kde = neighbors.KernelDensity(bandwidth=bandwidth, kernel = KDE_KERNEL).fit(sample)

points = FITTING_RANGE
# very slow if the dataset is too large, e.g. 100,000
# kde returns log prob, need to convert it
kde_result = exp(kde.score_samples(points))
print('bandwidth:', bandwidth, len(kde_result))
print(kde_result[:5])
bandwidth: 0.6 289
[  4.88690635e-08   1.04782434e-07   2.71497073e-07   4.19409578e-06
   2.46065046e-05]
In [48]:
# Plot jPDF
X = Y = PLOT_AXIS_RANGE
# Can't work if pass as generate_Z_from_X_Y(X,Y, exp(kde.score_samples())), need to use lambda
# see http://stackoverflow.com/questions/21035437/passing-a-function-as-an-argument-in-python
kde_Z = generate_Z_from_X_Y(X,Y, lambda coords: exp(kde.score_samples(coords)))
colorbar_lim = 0, kde_Z.max()

plot_3d_prob_density(X,Y,kde_Z)

fig_kde,ax1 = plt.subplots(figsize=(3.5,2.5))
plot_2d_prob_density(X,Y,kde_Z,xlabel='x'+speed_unit_text, ylabel='y'+speed_unit_text, ax=ax1)

with sns.axes_style({'axes.grid' : False}):
    from matplotlib import ticker
    fig_hist,ax2 = plt.subplots(figsize=(3.5,2.5))
    _,_,_,image = ax2.hist2d(df.x, df.y, bins=PLOT_AXIS_RANGE, cmap='viridis',)
    ax2.set_aspect('equal')
    cb = plt.colorbar(image)
    tick_locator = ticker.MaxNLocator(nbins=6)
    cb.locator = tick_locator
    cb.update_ticks()
    plt_configure(ax=ax2, xlabel='x'+speed_unit_text,ylabel='y'+speed_unit_text)
align_figures()
In [49]:
kde_cdf = cdf_from_pdf(kde_result)
config = {'bandwidth': bandwidth, 
          'fitting_range': FITTING_RANGE,
          'fit_limit': fit_limit,
          'kde_kernel': KDE_KERNEL}
In [50]:
%%time
gof_kde=Parallel(n_jobs=-1)(delayed(resampled_kde)(df, kde_result, config) 
                                       for i in arange(50)) 
Wall time: 14.6 s
In [51]:
for gof_name in [ 'R_square', 'K_S','Chi_square']:
    plt.figure(figsize=(4,3))
    pd.DataFrame(gof_kde)[gof_name].hist()
    plt_configure(title=gof_name)
align_figures()
In [52]:
# %%time
year_length = 5
gofs_bivariate = []
df_start_year, df_end_year = df_all_years.index.year[0], df_all_years.index.year[-1]
for start_year in arange(df_start_year, df_end_year-year_length):
    end_year = start_year+year_length-1
    df_previous = df_all_years[str(start_year):str(end_year)]
    speed_previous = array(list(zip(df_previous.x, df_previous.y)))
    kde2 = neighbors.KernelDensity(bandwidth=bandwidth, kernel=KDE_KERNEL).fit(speed_previous)
    kde_result2 = exp(kde2.score_samples(points))
    gofs_bivariate.append(goodness_of_fit_summary(kde_result2, kde_result))
gofs_bivariate=pd.DataFrame(gofs_bivariate)
gofs_bivariate.index = arange(df_start_year, df_end_year-year_length)
In [53]:
gofs_bivariate
Out[53]:
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
1979 83.377963 0.079192 3.846081e-06 0.111996 0.577609 0.722342
1980 0.861009 0.085279 4.050593e-06 0.114935 0.592767 0.707578
1981 74.912620 0.085267 4.472301e-06 0.120770 0.622860 0.677134
1982 35.287322 0.085126 4.539936e-06 0.121679 0.627552 0.672251
1983 34.825904 0.102621 4.482647e-06 0.120909 0.623580 0.676387
1984 54.653773 0.143219 1.500870e-05 0.221240 1.141028 -0.083514
1985 62.305633 0.128876 1.341427e-05 0.209158 1.078719 0.031592
1986 0.166021 0.083448 8.333527e-06 0.164857 0.850235 0.398383
1987 0.150571 0.091033 7.268268e-06 0.153960 0.794036 0.475287
1988 0.144991 0.104808 6.357396e-06 0.143990 0.742616 0.541045
1989 0.117007 0.087578 4.153698e-06 0.116388 0.600264 0.700135
1990 0.099880 0.078207 3.109111e-06 0.100695 0.519329 0.775546
1991 0.121132 0.096726 3.899796e-06 0.112775 0.581629 0.718465
1992 0.111910 0.088234 3.484494e-06 0.106601 0.549787 0.748446
1993 0.110048 0.077885 3.343384e-06 0.104420 0.538540 0.758633
1994 0.127404 0.083899 3.636174e-06 0.108897 0.561626 0.737496
1995 0.148099 0.092680 4.607589e-06 0.122583 0.632210 0.667367
1996 0.131386 0.085734 4.351752e-06 0.119131 0.614408 0.685837
1997 0.112509 0.081363 3.346846e-06 0.104474 0.538819 0.758383
1998 0.102862 0.086447 3.084864e-06 0.100302 0.517300 0.777296
1999 0.101312 0.087926 2.860224e-06 0.096581 0.498109 0.793514
2000 0.104879 0.086482 2.462765e-06 0.089620 0.462207 0.822207
2001 0.112423 0.087262 2.496167e-06 0.090225 0.465331 0.819796
2002 0.425294 0.099522 3.093975e-06 0.100450 0.518064 0.776639
2003 0.128985 0.097053 3.015343e-06 0.099165 0.511438 0.782315
2004 0.107995 0.092526 2.870103e-06 0.096748 0.498969 0.792801
2005 0.095498 0.088097 2.551269e-06 0.091216 0.470439 0.815818
2006 0.070024 0.074558 1.948541e-06 0.079716 0.411130 0.859330
2007 0.043544 0.051989 1.114274e-06 0.060282 0.310900 0.919558
2008 0.021209 0.026920 4.896805e-07 0.039962 0.206101 0.964649
2009 0.004595 0.015247 1.011572e-07 0.018163 0.093675 0.992697
In [54]:
gofs_bivariate.plot(y='R_square', figsize=(4,3))
gofs_bivariate.plot(y='K_S', figsize=(4,3))
align_figures()

univariate gof standard

In [55]:
def yearly_gof(df_all_years, start_year, end_year, density, y_ecdf, x):
    df_previous = df_all_years[str(start_year):str(end_year)]
    density_expected, _ = np.histogram(df_previous['speed'], bins=x, normed=True)
    r_square = sector_r_square(density, density_expected)
    
    ecdf_previous = sm.distributions.ECDF(df_previous['speed'])
    y_ecdf_previous = ecdf_previous(x)
    cdf_diff = (np.abs(y_ecdf - y_ecdf_previous))
    k_s = cdf_diff.max()
    return {'year': start_year, 'r_square': r_square, 'k_s': k_s}
In [56]:
x = arange(0, df.speed.max() + 1)
fig = plt.figure()
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)

for year_length in arange(5, 11):
    df_standard = df_all_years[str(2010):str(2014)]
    density, _ = np.histogram(df_standard['speed'], bins=x, normed=True)
    y_ecdf = sm.distributions.ECDF(df_standard.speed)(x)

    gofs = [yearly_gof(df_all_years, start_year, start_year+year_length-1, density, y_ecdf, x) 
            for start_year in arange(df_start_year, df_end_year-year_length)]

    gofs = pd.DataFrame(gofs)

    ax1.plot(gofs.year, gofs.r_square, label=year_length)
    ax2.plot(gofs.year, gofs.k_s, label=year_length)
plt.legend()
Out[56]:
<matplotlib.legend.Legend at 0x147e2710>

5. GMM by Expectation-maximization

In [57]:
sample= SPEED_SET
clf = mixture.GaussianMixture(n_components=NUMBER_OF_GAUSSIAN, covariance_type='full')
clf.fit(sample)
print(clf.converged_)
True
In [58]:
gmm_em_result = read_gmm_em_result(clf)
pretty_print_gmm(gmm_em_result)
Out[58]:
weight mean_x mean_y sig_x sig_y corr
1 0.435 2.817 -2.560 1.886 2.226 0.052
2 0.284 1.591 3.909 2.342 2.397 -0.227
3 0.281 -2.321 1.430 2.226 3.007 -0.157
In [59]:
fig,ax = plt.subplots(figsize=(3.5,3.5))
plot_gmm_ellipses(gmm_em_result, ax=ax, xlabel='x'+speed_unit_text, ylabel='y'+speed_unit_text)
GMM Plot Result
0.435268804803 [[ 2.81719111 -2.56025058]] [ 1.8773193   2.23299107] 171.311012934
0.283926975035 [[ 1.59115382  3.90859158]] [ 2.08163641  2.62686944] -137.917055152
0.280804220162 [[-2.32057427  1.4303464 ]] [ 2.16818007  3.0490281 ] -166.436142693
In [60]:
X = Y = PLOT_AXIS_RANGE
pdf_Z = generate_Z_from_X_Y(X,Y, lambda coords: exp(clf.score_samples(coords)))

def residule_between_kde_and_gmm(points):
    kde_vals = exp(kde.score_samples(points))
    gmm_vals = exp(clf.score_samples(points))
    return kde_vals - gmm_vals 

residual_Z = generate_Z_from_X_Y(X,Y, residule_between_kde_and_gmm)

plot_3d_prob_density(X,Y,pdf_Z)
plot_3d_prob_density(X,Y,residual_Z)
align_figures()

fig = plt.figure(figsize=(3.5,2.5))
plot_2d_prob_density(X,Y,kde_Z,xlabel='x'+speed_unit_text, ylabel='y'+speed_unit_text, colorbar_lim=colorbar_lim)
fig_em = plt.figure(figsize=(3.5,2.5))
plot_2d_prob_density(X,Y,pdf_Z,xlabel='x'+speed_unit_text, ylabel='y'+speed_unit_text, colorbar_lim=colorbar_lim)
fig = plt.figure(figsize=(3.5,2.5))
plot_2d_prob_density(X,Y,residual_Z,
                     xlabel='x'+speed_unit_text, ylabel='y'+speed_unit_text)
align_figures()

Goodness-of-fit Statistics

In [61]:
points = FITTING_RANGE
gmm_pdf_result = exp(clf.score_samples(points))
gof_df(gmm_pdf_result, kde_result)
Out[61]:
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.956 0.021 0.028 6.033753e-07 0.044 0.229
In [62]:
gmm_em = group_gmm_param_from_gmm_param_array(gmm_em_result, sort_group = True)
mixed_model_pdf_em = generate_gmm_pdf_from_grouped_gmm_param(gmm_em)

6. GMM by Optimization

In [63]:
sample = SPEED_SET
points = FITTING_RANGE
max_speed = df.speed.max()
print(FIT_METHOD)
square_error
In [64]:
# from GMM,EM 
# GMM format: weight, meanx, meany, sigx, sigy, rho
x0 = gmm_em_result

cons = [
        # sum of every 6th element, which is the fraction of each gaussian
        {'type': 'eq', 'fun': lambda x: sum(x[::6]) - 1},
        # # limit the width/height ratio of elliplse, optional
#         {'type': 'ineq', 'fun': lambda x: width_height_ratios_set(x) - 1/3},
#         {'type': 'ineq', 'fun': lambda x: 3 - width_height_ratios_set(x)},
]

bonds = [(0., 0.99),(-fit_limit, fit_limit),(-fit_limit, fit_limit),
         (0., fit_limit),(0., fit_limit),(-0.99, 0.99)]*(len(x0)//6)

result = sp.optimize.minimize(
    lambda x0: GMM_fit_score(x0, kde_result, points, FIT_METHOD),
    x0,
    bounds = bonds,
    constraints=cons,
    tol = 0.000000000001,
    options = {"maxiter": 500})
result
Out[64]:
     fun: -15.091855166834311
     jac: array([  1.94544005e+00,   4.76837158e-07,  -2.38418579e-07,
         0.00000000e+00,   0.00000000e+00,   3.57627869e-07,
         1.94544303e+00,  -1.19209290e-07,   1.19209290e-07,
        -2.38418579e-07,  -2.38418579e-07,  -1.19209290e-07,
         1.94543910e+00,  -1.19209290e-07,   0.00000000e+00,
         0.00000000e+00,   0.00000000e+00,   2.38418579e-07,
         0.00000000e+00])
 message: 'Optimization terminated successfully.'
    nfev: 1024
     nit: 50
    njev: 50
  status: 0
 success: True
       x: array([ 0.293899  ,  3.43561555, -1.88373487,  1.55735559,  2.52144546,
        0.228144  ,  0.40195895, -0.00854269,  3.79571906,  2.9427973 ,
        2.10745185, -0.02622996,  0.30414205,  0.1700162 , -2.0645803 ,
        3.13985328,  2.32147164, -0.49525453])

6.1 GMM Result

In [65]:
gmm = group_gmm_param_from_gmm_param_array(result.x, sort_group = True)
mixed_model_pdf = generate_gmm_pdf_from_grouped_gmm_param(gmm)
gmm_pdf_result = mixed_model_pdf(points)
pretty_print_gmm(gmm)
Out[65]:
weight mean_x mean_y sig_x sig_y corr
1 0.402 -0.009 3.796 2.943 2.107 -0.026
2 0.304 0.170 -2.065 3.140 2.321 -0.495
3 0.294 3.436 -1.884 1.557 2.521 0.228
In [66]:
fig_gmm, ax = plt.subplots(figsize=(3.5,3.5))
plot_gmm_ellipses(gmm, ax=ax, xlabel='x'+speed_unit_text, ylabel='y'+speed_unit_text)
GMM Plot Result
0.401958949329 [[-0.00854269  3.79571906]] [ 2.10596532  2.9438613 ] -92.2049590198
0.304142050464 [[ 0.1700162 -2.0645803]] [ 1.8380105   3.44523245] -119.12029985
0.293899000207 [[ 3.43561555 -1.88373487]] [ 1.4936114   2.55972042] 167.751933622

6.2 Goodness-of-fit statistics

In [67]:
gof_df(gmm_pdf_result, kde_result)
Out[67]:
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.980 0.013 0.021 2.790555e-07 0.030 0.156
In [68]:
X = Y = PLOT_AXIS_RANGE
pdf_Z = generate_Z_from_X_Y(X,Y, mixed_model_pdf)# passing a function as an argument

def residule_between_kde_and_gmm(points):
    kde_vals = exp(kde.score_samples(points))
    gmm_vals = mixed_model_pdf(points)
    return kde_vals - gmm_vals 

residual_Z = generate_Z_from_X_Y(X,Y, residule_between_kde_and_gmm)

plot_3d_prob_density(X,Y,pdf_Z)
plot_3d_prob_density(X,Y,residual_Z)
align_figures()

fig = plt.figure(figsize=(3.5,2.5))
plot_2d_prob_density(X,Y,kde_Z, xlabel='x'+speed_unit_text, ylabel='y'+speed_unit_text)
fig_gmm = plt.figure(figsize=(3.5,2.5))
plot_2d_prob_density(X,Y,pdf_Z, xlabel='x'+speed_unit_text, ylabel='y'+speed_unit_text)
fig = plt.figure(figsize=(3.5,2.5))
plot_2d_prob_density(X,Y,residual_Z,  xlabel='x'+speed_unit_text, ylabel='y'+speed_unit_text)
align_figures()
In [69]:
fig = plt.figure(figsize=(4.2,2.4))
ax1 = fig.add_subplot(1,2,1) 
plot_2d_prob_density(X, Y, kde_Z, ax=ax1,
                     xlabel='', ylabel='', colorbar=False)
ax1.grid(False)
ax2 = fig.add_subplot(1,2,2) 
plot_2d_prob_density(X, Y, pdf_Z, ax=ax2,
                     xlabel='', ylabel='', colorbar=False)
ax2.grid(False)
ax2.get_yaxis().set_visible(False)
In [70]:
def f(V,theta):
    return (mixed_model_pdf([[V*cos(theta),V*sin(theta)]]))*V

def f_em(V,theta):
    return (mixed_model_pdf_em([[V*cos(theta),V*sin(theta)]]))*V
In [71]:
%%time
x = arange(0, max_speed, 0.5)
_, y_weibull, y_cdf_weibull, weibull_params, y_ecdf = fit_weibull_and_ecdf(df.speed, x= x)
Wall time: 14.7 s
In [72]:
%%time
# Calculate Speed Distribution
# 1. GMM Model
y_ =[integrate.nquad(f, [[x_-0.01, x_+0.01],[0, 2*pi]]) for x_ in x]
y_gmm = array(list(zip(*y_))[0])*len(df.speed)/0.02

# y_ =[integrate.nquad(f_em, [[x_-0.01, x_+0.01],[0, 2*pi]]) for x_ in x]
# y_gmm_em = array(list(zip(*y_))[0])*len(df.speed)/0.02

# 2. Weibull
y_weibul = sp.stats.weibull_min.pdf(x, *weibull_params)

# 3. Plot Comparison
df['speed'].hist(bins=arange(0, df.speed.max()), alpha=0.5, label='Data')
plot(x, y_gmm,'-', color='black', label='GMM')
# plot(x, y_gmm_em,'-.', color='black', label='GMM EM')
plot(x, y_weibul*len(df.speed), '--', color='black', label='Weibull') 
print('Speed Distribution Comparison')
plt_configure(xlabel='Speed'+speed_unit_text,
              ylabel='Frequency',legend=True, figsize=(4, 2))
plt.gca().set_ylim(bottom = 0)
plt.tight_layout()
plt.locator_params(axis='y', nbins=5)

# 4. R square for GMM, Weibull
print(R_square_for_speed(df['speed'], f, weibull_params, f_em))
Speed Distribution Comparison
(0.98890256575186952, 0.97939352226805099, 0.98411944835927079)
Wall time: 8.76 s
In [73]:
%%time
y_ = [integrate.nquad(f, [[0, x_val],[0, 2*pi]]) for x_val in x]
y_cdf_gmm = array(list(zip(*y_))[0])

# y_em_ = [integrate.nquad(f_em, [[0, x_val],[0, 2*pi]]) for x_val in x]
# y_cdf_gmm_em = array(list(zip(*y_em_))[0])

# 5.2. CDF Comaprison
plot(x, y_ecdf,'o', alpha=0.8, label='Data')
plot(x, y_cdf_gmm,'-', color='black',label='GMM')
# plot(x, y_cdf_gmm_em,'-.', color='black',label='GMM EM')
plot(x, y_cdf_weibull,'--', color='black',label='Weibull')
plt_configure(xlabel = "V", ylabel='P', legend=True, figsize=(4,3))

plt.figure()
plot(log(x), log(-log(1-y_ecdf)),'o', label = 'Empirical')
plot(log(x), log(-log(1-y_cdf_weibull)),'--', label = 'Weibull')
plot(log(x), log(-log(1-y_cdf_gmm)),'-', color='black', label = 'GMM')
# plot(log(x), log(-log(1-y_cdf_gmm_em)),'-.', color='black', label = 'GMM EM')
plt_configure(xlabel='ln(V)',ylabel='ln(-ln(1-P))',legend={'loc':'best'}, figsize=(4,3))
align_figures()

cdf_diff, cdf_diff_weibull= np.abs(y_ecdf - y_cdf_gmm), np.abs(y_ecdf - y_cdf_weibull)
print(cdf_diff.max(), cdf_diff_weibull.max()) 
print(x[cdf_diff.argmax()], x[cdf_diff_weibull.argmax()])
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:15: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:16: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:17: RuntimeWarning: divide by zero encountered in log
0.0174235977985 0.0870329943917
2.0 5.0
Wall time: 8.92 s
In [74]:
# Calculate Angle Distribution
x = linspace(0,2*pi, num=36+1)
y_ =[integrate.nquad(f, [[0, inf],[x_-pi/36, x_+pi/36]]) for x_ in x]
y = array(list(zip(*y_))[0])*len(df['dir']) 

# y_em_ =[integrate.nquad(f_em, [[0, inf],[x_-pi/36, x_+pi/36]]) for x_ in x]
# y_em = array(list(zip(*y_em_))[0])*len(df['dir']) 

df['dir'].hist(bins=DIR_BIN, alpha=0.5, label='Data')
plot(x/pi*180, y,'-', color='black', label='GMM')
# plot(x/pi*180, y_em,'-.', color='black', label='GMM EM')
plt_configure(xlabel='Direction'+dir_unit_text, ylabel='Frequency', 
              legend={'loc': 'best'} ,tight='xtight',figsize = (4,2))
plt.tight_layout()
dir_fig = plt.gcf()
print('Direction Distribution Comparison')
Direction Distribution Comparison
In [75]:
%%time
incre = max(SECTOR_LENGTH, 10)
density_collection=Parallel(n_jobs=-1)(delayed(direction_compare)(gmm, df, angle, incre) 
                                        for angle in arange(0, 360, incre))  
# This R square is computed as in paper 
# Comparison of bivariate distribution constructionapproaches for analysing wind speed anddirection data
# http://onlinelibrary.wiley.com/doi/10.1002/we.400/full
print(true_R_square(density_collection))
0.91689252602
Wall time: 9.24 s

6.3 Sectoral Comaprison

In [77]:
# %%time
# curve_collection=Parallel(n_jobs=-1)(delayed(direction_compare2)
#                                      (gmm, df, angle, incre, complex=True) for angle in arange(start, end, incre))  
In [78]:
# Calculate Speed Distribution
def model_data_comparison(df, original_incre = 10, incre = 10):
    start, end = -original_incre/2 + incre/2, 360
    curve_collection = []
    max_speed = df.speed.max()
    
    # Find a max count for plotting histogram
    max_count = max_count_for_angles(df, start, end, incre)
    plot_range = [0, max_speed, 0, max_count*1.05]
    
    for angle in arange(start, end, incre):
        angle_radian, incre_radian = np.radians([angle, incre])  
        start_angle, end_angle = angle-incre/2, angle+incre/2
        
        # 0. Select data from observation
        sub_df, sub_max_speed = select_df_by_angle(df, start_angle, end_angle)
        data_size = len(sub_df.speed)
        # 1. Get Weibull and ECDF
        x, y_weibull, y_cdf_weibull, weibull_params, y_ecdf = fit_weibull_and_ecdf(sub_df.speed)
        # 2. Get GMM PDF, CDF
        _, y_gmm, y_cdf_gmm, direction_prob = gmm_integration_in_direction(f, angle_radian-incre_radian/2, angle_radian+incre_radian/2, x)
        
        # 3. R square for GMM, Weibull
        bins = arange(0, sub_df.speed.max()+1)
        density, _ = np.histogram(sub_df['speed'], bins=bins, normed=True)
        density_expected_gmm_ =[integrate.nquad(f, [[x_, x_+1],[angle_radian-incre_radian/2, angle_radian+incre_radian/2]]) 
                            for x_ in bins[:-1]]
        density_expected_gmm = array(list(zip(*density_expected_gmm_ ))[0])/direction_prob
        R_square_gmm = sector_r_square(density, density_expected_gmm)
        
        density_expected_weibull = sp.stats.weibull_min.cdf(bins[1:], *weibull_params) - sp.stats.weibull_min.cdf(bins[:-1], *weibull_params) 
        R_square_weibull = sector_r_square(density, density_expected_weibull)

        # 4. K-S for GMM, Weibull
        cdf_diff, cdf_diff_weibull= np.abs(y_ecdf - y_cdf_gmm), np.abs(y_ecdf - y_cdf_weibull)
                
        # 5. Make Plots
        fig = plt.figure(figsize=(10,1.9))
        # 5.1. Frequency Comparison
        ax1 = fig.add_subplot(1,3,1)        
        sub_df['speed'].hist(bins=arange(0, sub_max_speed), alpha=0.5, label='Data')                  
        plot(x, y_gmm*data_size,'-', color='black', label='GMM')
        plot(x, y_weibull*data_size, '--', color='black',label='Weibull')   
#         plt_configure(xlabel = "$V$", ylabel='Frequency', legend=True)
        plt_configure(xlabel = "V", ylabel='Frequency', legend=True)
        plt.axis(plot_range)
        
        # 5.2. CDF Comaprison
        ax2 = fig.add_subplot(1,3,2)
        plot(x, y_ecdf,'o', alpha=0.8, label='Data')
        plot(x, y_cdf_gmm,'-', color='black',label='GMM')
        plot(x, y_cdf_weibull,'--', color='black',label='Weibull')
        plt.gca().set_xlim(right = max_speed)
#         plt_configure(xlabel = "$V$", ylabel='$P$', legend=True)
        plt_configure(xlabel = "V", ylabel='P', legend=True)
        
        # 5.3. Weibull Comparison
#         ax3 = fig.add_subplot(1,3,3)
#         plot(log(x), log(-log(1-y_ecdf)),'o', alpha=0.8, label='Data')
#         plot(log(x), log(-log(1-y_cdf_gmm)),'-', color='black', label='GMM')
#         plot(log(x), log(-log(1-y_cdf_weibull)),'--',color='black',label='Weibull')
#         plt.gca().set_xlim(right = log(max_speed+1))
#         plt_configure(xlabel="ln(V)", ylabel="ln(-ln(1-P)",legend={'loc':'best'})
        
        curves = {'direction': angle, 'datasize': data_size, 'weight': direction_prob, 'x': x, 
                  'gmm_pdf': y_gmm, 'gmm_cdf': y_cdf_gmm,
                  'weibull_pdf': y_weibull, 'weibull_cdf': y_cdf_weibull, 'ecdf': y_ecdf,
                  'max_cdf_diff_gmm': cdf_diff.max(), 'max_cdf_diff_weibull': cdf_diff_weibull.max(), 
                  'r_square_gmm': R_square_gmm, 'r_square_weibull': R_square_weibull}
        curve_collection.append(curves)
        
        plt.tight_layout()
        plt.show()
        print('%s (%s - %s) degree' % (angle, start_angle, end_angle))
        print('data size:', len(sub_df), 'weight', len(sub_df)/len(df))
        print('GMM', 'Weibull')
        print('R square', R_square_gmm,  R_square_weibull)
        print('max diff:', cdf_diff.max(), cdf_diff_weibull.max(), 
              'speed value:', x[cdf_diff.argmax()], x[cdf_diff_weibull.argmax()], 'y gmm', y_cdf_gmm[cdf_diff.argmax()])
        print(' ')
    return curve_collection
In [79]:
%%time
if len(effective_column) == 16:
    rebinned_angle = 22.5
else: 
    rebinned_angle = 20
    
curve_collection = model_data_comparison(df, SECTOR_LENGTH, rebinned_angle)
5.0 (-5.0 - 15.0) degree
data size: 1436 weight 0.032901821514491926
GMM Weibull
R square 0.964740941178 0.949638690826
max diff: 0.0429345083928 0.0648564253622 speed value: 2.48576283043 2.48576283043 y gmm 0.159926151847
 
25.0 (15.0 - 35.0) degree
data size: 2152 weight 0.049306908007790126
GMM Weibull
R square 0.878567739353 0.938490360103
max diff: 0.0812945606855 0.0546608942477 speed value: 4.71349310678 4.71349310678 y gmm 0.573909900281
 
45.0 (35.0 - 55.0) degree
data size: 2636 weight 0.060396379883148124
GMM Weibull
R square 0.951102250673 0.978956392805
max diff: 0.0408990765313 0.0931474093462 speed value: 2.62356732998 5.90302649246 y gmm 0.152811064392
 
65.0 (55.0 - 75.0) degree
data size: 2514 weight 0.05760109978233475
GMM Weibull
R square 0.979001441204 0.978908327488
max diff: 0.0514405256701 0.0917511435006 speed value: 6.14811332715 5.46498962413 y gmm 0.752713397587
 
85.0 (75.0 - 95.0) degree
data size: 3940 weight 0.09027379997708787
GMM Weibull
R square 0.95464178632 0.971363539767
max diff: 0.0694943816297 0.073955349667 speed value: 6.68420359353 5.19882501719 y gmm 0.835230422239
 
105.0 (95.0 - 115.0) degree
data size: 3173 weight 0.07270019475312178
GMM Weibull
R square 0.882358131473 0.956698713467
max diff: 0.10689667377 0.0884767559145 speed value: 4.1455965717 4.1455965717 y gmm 0.370254287466
 
125.0 (115.0 - 135.0) degree
data size: 2938 weight 0.06731584373925993
GMM Weibull
R square 0.947060207825 0.946200575371
max diff: 0.0659010549222 0.154129792506 speed value: 3.02256051189 6.04512102377 y gmm 0.195921476978
 
145.0 (135.0 - 155.0) degree
data size: 1521 weight 0.034849352732271736
GMM Weibull
R square 0.921876111813 0.956938430288
max diff: 0.0546097683259 0.145727044762 speed value: 4.39605333189 5.1287288872 y gmm 0.472755724933
 
165.0 (155.0 - 175.0) degree
data size: 1506 weight 0.03450567075266354
GMM Weibull
R square 0.931464437447 0.930867876842
max diff: 0.0434529542676 0.0688944790526 speed value: 4.31286640049 4.31286640049 y gmm 0.543532437499
 
185.0 (175.0 - 195.0) degree
data size: 1107 weight 0.025363730095085347
GMM Weibull
R square 0.913750761568 0.933577241471
max diff: 0.0819331124746 0.0565516255432 speed value: 3.76638746702 3.76638746702 y gmm 0.531436354553
 
205.0 (195.0 - 215.0) degree
data size: 1124 weight 0.02575323633864131
GMM Weibull
R square 0.938692046031 0.939994507064
max diff: 0.033175774531 0.101827464861 speed value: 4.10177210115 3.64601964547 y gmm 0.689244154295
 
225.0 (215.0 - 235.0) degree
data size: 1062 weight 0.02433268415626074
GMM Weibull
R square 0.952809578603 0.976484959751
max diff: 0.0475340950386 0.0630337045847 speed value: 1.52931315499 3.05862630998 y gmm 0.139848202513
 
245.0 (235.0 - 255.0) degree
data size: 877 weight 0.020093939741092907
GMM Weibull
R square 0.894153026115 0.994563135236
max diff: 0.0879974447517 0.0366962024237 speed value: 1.80820263596 0.602734211986 y gmm 0.187943262204
 
265.0 (255.0 - 275.0) degree
data size: 1593 weight 0.03649902623439111
GMM Weibull
R square 0.969097342546 0.985381139632
max diff: 0.0441427618683 0.105274805422 speed value: 4.95223059001 3.85173490334 y gmm 0.789277727342
 
285.0 (275.0 - 295.0) degree
data size: 2641 weight 0.060510940543017526
GMM Weibull
R square 0.95666040805 0.966808887619
max diff: 0.042423811815 0.0762103594917 speed value: 3.57213329398 3.57213329398 y gmm 0.326754529722
 
305.0 (295.0 - 315.0) degree
data size: 4987 weight 0.1142628021537404
GMM Weibull
R square 0.994115551373 0.991212802637
max diff: 0.0108712175829 0.101112413718 speed value: 1.99538362466 5.98615087399 y gmm 0.0608010351084
 
325.0 (315.0 - 335.0) degree
data size: 4622 weight 0.10589987398327415
GMM Weibull
R square 0.956772480996 0.970197580066
max diff: 0.0610152866281 0.063226261474 speed value: 4.99577279678 4.99577279678 y gmm 0.582212753182
 
345.0 (335.0 - 355.0) degree
data size: 3270 weight 0.07492267155458815
GMM Weibull
R square 0.97190797942 0.96232127491
max diff: 0.0458092042269 0.0543016105641 speed value: 2.89009967836 5.05767443713 y gmm 0.200243454991
 
Wall time: 48.4 s
In [80]:
diff_df = pd.DataFrame(curve_collection) 

gmm_mean, weibull_mean = plot_sectoral_comparison(diff_df.r_square_gmm, diff_df.r_square_weibull, 
                                                  diff_df.direction, diff_df.datasize)
plt_configure(ylabel="$\ R^2$", xlabel='Direction'+dir_unit_text)
ylim = min(plt.gca().get_ylim()[0],0.75)
plt.gca().set_ylim(top=1, bottom=ylim)
plt.tight_layout()
print(gmm_mean, weibull_mean)
0.9486013526849786 0.9657180263849882
In [81]:
gmm_mean, weibull_mean = plot_sectoral_comparison(diff_df.max_cdf_diff_gmm, diff_df.max_cdf_diff_weibull, 
                                                  diff_df.direction, diff_df.datasize)
plt_configure(ylabel="K-S", xlabel='Direction'+dir_unit_text)
ylim = max(plt.gca().get_ylim()[1],0.25)
plt.gca().set_ylim(top=ylim, bottom=0)
plt.tight_layout()
print(gmm_mean, weibull_mean)
0.05459221622186945 0.08484011588860128
In [82]:
# Compare direction weight with previous figure
display(dir_fig)

6.4 Insufficient-fit Sector Investigation

6.4.1 Data Variability, by Bootstrap (Resampling)

In [83]:
angle =  max_diff_angle = diff_df.ix[diff_df['max_cdf_diff_gmm'].idxmax()]['direction']
incre = rebinned_angle
In [84]:
FRACTION = 1

# Select data from observation
start_angle, end_angle = angle-incre/2, angle+incre/2
angle_radian, incre_radian = radians(angle), radians(incre)  
sub_df, sub_max_speed = select_df_by_angle(df, start_angle, end_angle)
In [85]:
x = arange(0, sub_max_speed, 0.5)
_, y_weibull, y_cdf_weibull, weibull_params, y_ecdf = fit_weibull_and_ecdf(sub_df.speed, x)
_, y_gmm, y_cdf_gmm, direction_prob = gmm_integration_in_direction(f, angle_radian-incre_radian/2, angle_radian+incre_radian/2, x)

fig = plt.figure(figsize=(10,1.9))
ax1 = fig.add_subplot(1,3,1)   
ax2 = fig.add_subplot(1,3,2)   
ax3 = fig.add_subplot(1,3,3)   

# 1. Data
bins=arange(0, sub_max_speed)
sub_df['speed'].hist(ax=ax1, bins=bins, alpha=0.5, label='Data', normed=True)  

# 2. GMM
ax1.plot(x, y_gmm,'-', color='black', label='GMM')
ax2.plot(x, y_cdf_gmm,'-', color = 'black', label='GMM')
ax3.plot(log(x), log(-log(1-y_cdf_gmm)),'-', color = 'black',label='GMM')

# 3. Weilbull 
ax1.plot(x, y_weibull,'--',color='black',label='Weibull')
ax2.plot(x, y_cdf_weibull,'--',label='Weibull')
ax3.plot(log(x), log(-log(1-y_cdf_weibull)),'--',label='Weibull')

# 4. Data Resampled
count_collection = []
for i in range(1,100):
    sub_df_resampled = sub_df.sample(frac=FRACTION, replace=True)    
    resampled_count, _ = np.histogram(sub_df_resampled['speed'], bins=bins, normed=True) 
    count_collection.append(resampled_count)
    
    ecdf = sm.distributions.ECDF(sub_df_resampled.speed)
    y_ecdf = ecdf(x) 
    ax2.plot(x, y_ecdf,':', label='Data Resampled')
    ax3.plot(log(x), log(-log(1-y_ecdf)),':', label='Data Resampled')
    if i == 1: 
#         plt_configure(ax=ax2, xlabel = "$V$", ylabel='$P$', legend={'loc':'best'})
#         plt_configure(ax=ax3, xlabel="ln($V$)", ylabel="ln(-ln(1-$P$)",legend={'loc':'best'})
        plt_configure(ax=ax2, xlabel = "V", ylabel='P', legend={'loc':'best'})
        plt_configure(ax=ax3, xlabel="ln(V)", ylabel="ln(-ln(1-P)",legend={'loc':'best'})

print('%s (%s - %s) Degree Speed Distribution' % (angle, start_angle, end_angle))
count_collection = np.array(count_collection)
mx, mn = np.max(count_collection,0), np.min(count_collection,0)
ax1.plot(bins[1:]-0.5, mx, ':', color='blue')
ax1.plot(bins[1:]-0.5, mn, ':', color='blue', label='Resample limit')
ax1.set_ylim(bottom = 0)
# plt_configure(ax=ax1, xlabel='$V$',ylabel='Frequency',legend={'loc':'best'})
plt_configure(ax=ax1, xlabel='V', ylabel='Frequency',legend={'loc':'best'})
ax1.locator_params(axis='y', nbins=5)
ax2.locator_params(axis='y', nbins=5)
ax3.locator_params(axis='y', nbins=5)
plt.tight_layout()
diff = abs(y_ecdf - y_cdf_gmm)
print(diff.max(), x[diff.argmax()], y_cdf_gmm[diff.argmax()])
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:17: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:22: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:34: RuntimeWarning: divide by zero encountered in log
105.0 (95.0 - 115.0) Degree Speed Distribution
0.117433475535 4.5 0.439767911165

6.4.2 Time Variability

In [86]:
fig_time_variability_3d = plt.figure()
ax1 = fig_time_variability_3d.gca(projection='3d')

fig_time_variability_cdf,ax2 = plt.subplots(figsize=(3,1.8))
fig_time_variability_weibull, ax3 = plt.subplots(figsize=(3,1.8))

ax2.plot(x, y_cdf_gmm,'-', color='black', label = 'GMM')
ax2.plot(x, y_cdf_weibull,'--', label='Weibull')

ax3.plot(log(x), log(-log(1-y_cdf_gmm)),'-', color='black',label='GMM')
ax3.plot(log(x), log(-log(1-y_cdf_weibull)), '--', label='Weibull')

# 3. Data
prop_cycle=iter(mpl.rcParams['axes.color_cycle'])
for start_time in range(20000000, 20150000, 50000):
    end_time = start_time + 50000 
    time_label = start_time//10000
    df_other_years = df_all_years.query('(date >= @start_time) & (date < @end_time)')
    df_other_years_at_angle, sub_max_speed_other_year = select_df_by_angle(df_other_years, start_angle, end_angle)
    if len(df_other_years_at_angle) > 0 :
        
        ecdf = sm.distributions.ECDF(df_other_years_at_angle.speed)
        y_ecdf = ecdf(x)
        ax2.plot(x, y_ecdf,':', label = time_label)
        ax3.plot(log(x), log(-log(1-y_ecdf)),':', label = time_label)
        
        title = '%s - %s' %(time_label, time_label+4)
        count, division = np.histogram(df_other_years_at_angle['speed'], normed=True,
                                       bins=arange(0, sub_max_speed_other_year))
        ax1.bar(left=division[:-1], height=count, zs=time_label, zdir='x', 
                color=next(prop_cycle), alpha=0.8)
        x_3d = time_label*np.ones_like(x)
        ax1.plot(x_3d, x, y_gmm, '-', color='black', label='GMM'  if time_label == 2010 else '')
        ax1.plot(x_3d, x, y_weibull, '--', color='blue', label='Weibull' if time_label == 2010 else '')
        
print('%s (%s - %s) Degree Speed Distribution' % (angle, start_angle, end_angle))
ax1.set_ylim(bottom = 0)
ax1.set_zlabel('Frequency')
plt_configure(ax=ax1, xlabel='Time',ylabel='V', legend=True)
# plt_configure(ax=ax2, xlabel = "$V$", ylabel='$P$', legend={'loc':'best'})
# plt_configure(ax=ax3, xlabel="ln($V$)", ylabel="ln(-ln(1-$P$)", legend={'loc':'best'})
plt_configure(ax=ax2, xlabel = "V", ylabel='P', legend={'loc':'best'})
plt_configure(ax=ax3, xlabel="ln(V)", ylabel="ln(-ln(1-P)", legend={'loc':'best'})

ax1.set_zlim(bottom = 0)
align_figures()
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:10: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:11: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:25: RuntimeWarning: divide by zero encountered in log
105.0 (95.0 - 115.0) Degree Speed Distribution

6.4.3 Adjacent Sector Variability

In [87]:
incre = rebinned_angle
angle_group = [max_diff_angle-incre, max_diff_angle, max_diff_angle+incre]
In [88]:
fig_adjecent_variability_3d = plt.figure()
ax1 = fig_adjecent_variability_3d.gca(projection='3d')
fig_adjecent_variability_cdf, ax2 = plt.subplots(figsize=(3,1.8))
fig_adjecent_variability_weibull, ax3 = plt.subplots(figsize=(3,1.8))

legend_3d = False
prop_cycle=iter(mpl.rcParams['axes.color_cycle'])

curve_df = pd.DataFrame(curve_collection)

for angle in angle_group:
    curves = curve_df.query('direction == @angle%360').T.to_dict()
    curves = curves[list(curves)[0]]
    data_size, x =  curves['datasize'], curves['x']
    y_gmm, y_cdf_gmm =  curves['gmm_pdf'], curves['gmm_cdf'] 
    y_weibull, y_cdf_weibull, y_cdf = curves['weibull_pdf'],  curves['weibull_cdf'], curves['ecdf']

    linestyle = '-' if angle == max_diff_angle else ':'
    alpha = 0.7 if angle == max_diff_angle else 0.3

    ax2.plot(x, y_gmm*data_size, linestyle, label=angle)        
    ax3.plot(x, y_weibull*data_size, linestyle, label=angle)

    start_angle, end_angle = angle-incre/2, angle+incre/2
    sub_df, sub_max_speed = select_df_by_angle(df, start_angle, end_angle)

    x_3d = angle*np.ones_like(x)
    ax1.plot(x_3d, x, y_gmm*data_size, color='black', label='GMM')
    ax1.plot(x_3d, x, y_weibull*data_size, color='blue', linestyle='--',label='Weibull')

    count, division = np.histogram(sub_df['speed'], bins=arange(0, sub_max_speed))
    ax1.bar(left=division[:-1], height=count, zs=angle, zdir='x', color=next(prop_cycle), alpha=0.8)

    if legend_3d == False:
        ax1.legend()
        legend_3d = True
        
plt_configure(ax=ax1, xlabel='Direction', ylabel='Speed')   
plt_configure(ax=ax2, xlabel='V',ylabel='Frequency',legend={'loc':'best'})
plt_configure(ax=ax3, xlabel='V',ylabel='Frequency',legend={'loc':'best'})
ax1.set_zlabel('Frequency')
ax1.set_zlim(bottom = 0)
ylim = max(ax1.get_ylim()[1],ax3.get_ylim()[1])
ax2.set_ylim(bottom = 0, top=ylim)
ax3.set_ylim(bottom = 0, top=ylim)

print(max_diff_angle) 
print('GMM, Weibull, Histogram')
align_figures()
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
105.0
GMM, Weibull, Histogram

7. Result Variability & Cross-Validation

In [89]:
if 'bandwidth' not in globals():
    bandwidth = DEFAULT_BANDWDITH    
if 'FIT_METHOD' not in globals():
    FIT_METHOD = 'square_error'       
if 'KDE_KERNEL' not in globals():
    KDE_KERNEL = 'gaussian'
    
config = {'bandwidth': bandwidth, 
          'fitting_range': FITTING_RANGE,
          'fit_limit': fit_limit,
          'kde_kernel': KDE_KERNEL}

print(bandwidth, FIT_METHOD)
0.6 square_error

7.1 Variability of the Result

In [90]:
%%time
results = Parallel(n_jobs=-1)(delayed(resampled_fitting)(df, FIT_METHOD, NUMBER_OF_GAUSSIAN, config) for i in range(10))                        
for result in results:
    display(pretty_print_gmm(result['gmm']))
    fig,ax = plt.subplots(figsize=(3.5,3.5))
    plot_gmm_ellipses(result['gmm'],ax=ax, xlabel='x'+speed_unit_text, ylabel='y'+speed_unit_text)
    plt.show()
    
    display(gof_df(result['gmm_pdf_result'], result['kde_result']))
    display(gof_df(result['gmm_pdf_result'], kde_result))
    print('')
weight mean_x mean_y sig_x sig_y corr
1 0.408 -0.176 3.790 2.992 2.135 0.041
2 0.307 3.449 -2.005 1.571 2.733 0.221
3 0.285 0.158 -1.982 2.966 2.103 -0.402
GMM Plot Result
0.407880147874 [[-0.17636022  3.79044899]] [ 2.13115278  2.99486087] -86.6353401103
0.307285105818 [[ 3.44863638 -2.00452144]] [ 1.51447021  2.76488168] 169.634105551
0.284834746308 [[ 0.15821747 -1.9816233 ]] [ 1.81196262  3.15208756] -114.438340022
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.979 0.012 0.022 2.824881e-07 0.031 0.157
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.979 0.012 0.022 2.898707e-07 0.031 0.159

weight mean_x mean_y sig_x sig_y corr
1 0.409 -0.023 3.762 2.935 2.135 -0.048
2 0.299 0.188 -2.197 3.111 2.359 -0.519
3 0.292 3.456 -1.800 1.577 2.420 0.233
GMM Plot Result
0.409269869582 [[-0.02251835  3.76222113]] [ 2.12944227  2.93841958] -94.2010409128
0.298830241353 [[ 0.18814923 -2.19663838]] [ 1.81518342  3.45672899] -120.802972514
0.291899889065 [[ 3.45569442 -1.79962256]] [ 1.50587475  2.46539574] 166.09274751
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.977 0.014 0.026 3.156841e-07 0.033 0.166
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.979 0.013 0.022 2.849524e-07 0.030 0.157

weight mean_x mean_y sig_x sig_y corr
1 0.408 0.217 3.794 3.015 2.094 -0.095
2 0.311 0.134 -2.138 3.147 2.642 -0.556
3 0.281 3.430 -1.947 1.583 2.229 0.194
GMM Plot Result
0.407736994196 [[ 0.21666487  3.79434082]] [ 2.07596493  3.0277824 ] -97.1611837526
0.311425019503 [[ 0.13386781 -2.13847803]] [ 1.8956016   3.64532902] -126.232484348
0.2808379863 [[ 3.4302196  -1.94666934]] [ 1.52624097  2.26838989] 165.439741143
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.980 0.011 0.024 2.754687e-07 0.031 0.155
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.979 0.012 0.021 2.894194e-07 0.031 0.158

weight mean_x mean_y sig_x sig_y corr
1 0.410 -0.120 3.746 2.944 2.140 0.024
2 0.311 3.392 -1.982 1.581 2.735 0.270
3 0.279 0.252 -2.036 3.107 2.074 -0.440
GMM Plot Result
0.410393514229 [[-0.11969412  3.74570342]] [ 2.13841239  2.94527652] -87.9142715381
0.310613317754 [[ 3.39208023 -1.98180376]] [ 1.4966208   2.78214115] 167.448539848
0.278993168017 [[ 0.25225444 -2.03626999]] [ 1.75411208  3.29847746] -113.338158049
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.979 0.012 0.028 2.946865e-07 0.031 0.160
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.980 0.012 0.026 2.822933e-07 0.030 0.156

weight mean_x mean_y sig_x sig_y corr
1 0.397 -0.053 3.789 2.892 2.089 -0.028
2 0.307 0.212 -2.020 3.146 2.294 -0.477
3 0.296 3.423 -1.915 1.580 2.569 0.232
GMM Plot Result
0.396517257373 [[-0.05263585  3.78918169]] [ 2.08739749  2.89290477] -92.4002650962
0.306993997297 [[ 0.21201064 -2.01967847]] [ 1.85152043  3.42514973] -118.048430354
0.296488745329 [[ 3.42302979 -1.91512879]] [ 1.51330698  2.60902996] 167.686162732
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.980 0.013 0.021 2.838901e-07 0.031 0.157
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.980 0.015 0.021 2.826977e-07 0.030 0.157

weight mean_x mean_y sig_x sig_y corr
1 0.407 -0.072 3.792 2.901 2.142 -0.005
2 0.316 3.346 -1.957 1.612 2.676 0.227
3 0.278 0.158 -1.978 3.187 2.152 -0.492
GMM Plot Result
0.406990079969 [[-0.07218619  3.79174155]] [ 2.14207261  2.90133015] -90.4388309209
0.315501820758 [[ 3.34597255 -1.95736869]] [ 1.54845218  2.71336794] 168.37648868
0.277508099272 [[ 0.1577784 -1.97779  ]] [ 1.74147091  3.42869842] -115.349181433
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.978 0.011 0.026 3.055631e-07 0.031 0.163
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.979 0.011 0.028 2.876908e-07 0.031 0.158

weight mean_x mean_y sig_x sig_y corr
1 0.407 -0.178 3.780 2.928 2.141 0.016
2 0.328 3.353 -2.041 1.639 2.698 0.221
3 0.264 0.073 -1.963 3.071 2.030 -0.423
GMM Plot Result
0.407274485171 [[-0.17775344  3.7804764 ]] [ 2.14031926  2.92797063] -88.5785687704
0.328397392732 [[ 3.35302176 -2.04118283]] [ 1.57637514  2.73516563] 168.459603935
0.264328122097 [[ 0.07283633 -1.96329024]] [ 1.7414935   3.24361879] -112.421550766
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.980 0.011 0.025 2.755604e-07 0.030 0.154
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.979 0.012 0.025 2.861295e-07 0.031 0.158

weight mean_x mean_y sig_x sig_y corr
1 0.400 -0.146 3.771 2.895 2.080 0.016
2 0.320 3.385 -1.983 1.605 2.716 0.260
3 0.280 0.146 -1.950 3.188 2.030 -0.432
GMM Plot Result
0.400273103376 [[-0.14553874  3.77130772]] [ 2.07980008  2.89568563] -88.6767754992
0.320044874312 [[ 3.38483157 -1.98274364]] [ 1.52419328  2.7627381 ] 167.356005899
0.279682022312 [[ 0.14595764 -1.94952312]] [ 1.73962592  3.35529148] -111.393202998
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.978 0.014 0.028 3.029477e-07 0.030 0.162
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.979 0.015 0.028 2.867399e-07 0.031 0.158

weight mean_x mean_y sig_x sig_y corr
1 0.401 0.261 3.769 2.916 2.085 -0.077
2 0.320 0.066 -2.136 3.242 2.635 -0.583
3 0.278 3.481 -1.895 1.566 2.246 0.193
GMM Plot Result
0.401198415579 [[ 0.26078537  3.76890473]] [ 2.07280816  2.92459501] -96.3653054476
0.320320348942 [[ 0.06558588 -2.13613728]] [ 1.85311084  3.74470409] -125.147654877
0.278481235479 [[ 3.48076398 -1.89513068]] [ 1.51185663  2.28262236] 166.150671252
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.978 0.014 0.023 2.989677e-07 0.032 0.161
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.979 0.014 0.022 2.913604e-07 0.031 0.159

weight mean_x mean_y sig_x sig_y corr
1 0.407 -0.032 3.765 2.942 2.095 -0.029
2 0.299 0.136 -2.074 3.111 2.270 -0.488
3 0.294 3.470 -1.835 1.548 2.570 0.196
GMM Plot Result
0.407171525456 [[-0.03234511  3.76495884]] [ 2.09311469  2.94362141] -92.4183818897
0.298739246709 [[ 0.1361459  -2.07404123]] [ 1.81467001  3.39626131] -118.354742898
0.294089227835 [[ 3.46984824 -1.83523985]] [ 1.50191461  2.59706366] 169.817194447
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.978 0.013 0.022 2.980594e-07 0.032 0.161
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.979 0.014 0.023 2.879462e-07 0.031 0.158
Wall time: 13.8 s

7.2 Cross-validation, to select the number of Gaussian

In [91]:
%%time
from sklearn.cross_validation import train_test_split, KFold

## 5-fold cross validation
gaussian_number_range = arange(1,6)
CV_result_train_all,CV_result_test_all =[],[]
number_of_fold = 4
print('Number of train/test dataset', len(df)*(number_of_fold-1)/number_of_fold, len(df)/number_of_fold) 

for number_of_gaussian in gaussian_number_range:
    print( '  ')
    print('Number of gaussian', number_of_gaussian)
    
    kf = KFold(len(df), n_folds=number_of_fold, shuffle=True) 

    CV_result = Parallel(n_jobs=-1)(delayed(fit_per_fold)(df, train_index, test_index, FIT_METHOD, number_of_gaussian, config) for train_index, test_index in kf)                        

    CV_result_train, CV_result_test = list(zip(*CV_result))
    CV_result_train, CV_result_test = list(CV_result_train), list(CV_result_test)
        
    CV_result_train_all.append(CV_result_train)
    CV_result_test_all.append(CV_result_test)
    
    print('Train')
    pretty_pd_display(CV_result_train)
    print('Test')
    pretty_pd_display(CV_result_test)
Number of train/test dataset
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
  "This module will be removed in 0.20.", DeprecationWarning)
 32733.75 10911.25
  
Number of gaussian 1
Train
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.122142 0.070514 0.000003 0.103915 0.536396 0.760733
1 0.120929 0.070357 0.000003 0.102883 0.532850 0.764013
2 0.121155 0.069441 0.000003 0.103001 0.531562 0.764660
3 0.124350 0.071850 0.000003 0.104953 0.538193 0.759006
Test
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.124302 0.069571 0.000003 0.102524 0.527395 0.768713
1 0.129919 0.078910 0.000003 0.107457 0.547197 0.751106
2 0.130900 0.071008 0.000003 0.106983 0.550689 0.749445
3 0.120898 0.064357 0.000003 0.100632 0.527909 0.769078
  
Number of gaussian 2
Train
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.046328 0.030088 6.624027e-07 0.046003 0.239736 0.952580
1 0.047376 0.029279 6.628999e-07 0.046610 0.239850 0.951958
2 0.046211 0.029894 6.735108e-07 0.046563 0.241665 0.951378
3 0.049579 0.030620 6.870869e-07 0.048030 0.244104 0.950244
Test
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.055949 0.029933 7.493495e-07 0.051016 0.254872 0.944739
1 0.051299 0.034474 7.394417e-07 0.048751 0.253107 0.947420
2 0.051738 0.029830 7.359662e-07 0.049970 0.252816 0.947168
3 0.046541 0.027746 6.768111e-07 0.045032 0.242397 0.951798
  
Number of gaussian 3
Train
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.021219 0.012068 2.733721e-07 0.029812 0.154011 0.980301
1 0.019864 0.012789 2.873223e-07 0.030647 0.157853 0.979242
2 0.023544 0.013631 2.851327e-07 0.030138 0.157194 0.979606
3 0.023478 0.013847 2.817655e-07 0.030689 0.156418 0.979475
Test
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.025692 0.013261 3.660132e-07 0.034714 0.178125 0.973547
1 0.025759 0.014848 3.206323e-07 0.032224 0.166840 0.977002
2 0.040954 0.017355 3.463950e-07 0.034846 0.173599 0.974405
3 0.023584 0.011091 3.382350e-07 0.032037 0.171032 0.976322
  
Number of gaussian 4
Train
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.020096 0.012072 2.391270e-07 0.027913 0.144110 0.982627
1 0.018529 0.012738 2.478553e-07 0.028115 0.146669 0.982249
2 0.025536 0.009368 2.204376e-07 0.026905 0.138260 0.984085
3 0.018092 0.010768 2.403998e-07 0.028233 0.144309 0.982648
Test
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.025619 0.009874 3.251032e-07 0.032607 0.167637 0.977073
1 0.024259 0.012630 3.037479e-07 0.032572 0.162196 0.977667
2 0.030759 0.020605 3.092995e-07 0.031435 0.163879 0.977785
3 0.022958 0.015892 3.177498e-07 0.031413 0.166367 0.977172
  
Number of gaussian 5
Train
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.016969 0.007243 1.738511e-07 0.023957 0.122735 0.987455
1 0.017073 0.009355 1.942943e-07 0.024399 0.129843 0.985997
2 0.020132 0.008453 1.744303e-07 0.023986 0.123035 0.987354
3 0.034381 0.007988 1.477747e-07 0.022400 0.113244 0.989374
Test
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.028990 0.010562 2.083806e-07 0.025602 0.134677 0.984987
1 0.022552 0.009674 3.099754e-07 0.035135 0.163907 0.977654
2 0.025451 0.009292 2.287937e-07 0.026861 0.140789 0.983769
3 0.031718 0.014668 2.636428e-07 0.027665 0.151134 0.980873
Wall time: 45.1 s
In [92]:
train_scores_mean, train_scores_std = generate_mean_std_gof(CV_result_train_all)
print('Train gof mean, std')
display(train_scores_mean)

test_scores_mean, test_scores_std = generate_mean_std_gof(CV_result_test_all)
print('Test gof mean, std')
display(test_scores_mean)
Train gof mean, std
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
1 0.122144 0.070540 3.296584e-06 0.103688 0.534750 0.762103
2 0.047373 0.029970 6.714751e-07 0.046801 0.241339 0.951540
3 0.022026 0.013084 2.818981e-07 0.030321 0.156369 0.979656
4 0.020563 0.011236 2.369549e-07 0.027792 0.143337 0.982902
5 0.022139 0.008260 1.725876e-07 0.023686 0.122214 0.987545
Test gof mean, std
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
1 0.126504 0.070962 3.341793e-06 0.104399 0.538297 0.759585
2 0.051382 0.030496 7.253921e-07 0.048692 0.250798 0.947781
3 0.028997 0.014139 3.428189e-07 0.033455 0.172399 0.975319
4 0.025899 0.014750 3.139751e-07 0.032007 0.165020 0.977424
5 0.027178 0.011049 2.526981e-07 0.028816 0.147627 0.981821
In [93]:
prop_cycle=mpl.rcParams['axes.color_cycle']
gaussian_number_range = train_scores_mean.index
for column, column_name in zip(['R_square','K_S','Chi_square'],["$\ R^2$", "K-S", "$\widetilde{\chi^2} $"]):
    plot(gaussian_number_range, train_scores_mean[column],
             '--', label = 'training', color=prop_cycle[0])
    plt.fill_between(gaussian_number_range, 
                     train_scores_mean[column] - train_scores_std[column],
                     train_scores_mean[column] + train_scores_std[column], 
                     alpha=0.2, color=prop_cycle[0])
    
    plot(gaussian_number_range, test_scores_mean[column],
             '-', label = 'test',color=prop_cycle[1])
    plt.fill_between(gaussian_number_range, 
                 test_scores_mean[column] - test_scores_std[column],
                 test_scores_mean[column] + test_scores_std[column], 
                 alpha=0.2,color=prop_cycle[1])
    plt.xticks(gaussian_number_range)
    print(column)
    plt.locator_params(axis='y', nbins=5)
    plt_configure(xlabel='Number of Gaussian Distributions', ylabel=column_name, 
                  figsize=(3,2), legend={'loc':'best'})
    if column == 'R_square':
        plt.gca().set_ylim(top=1)
    if column == 'K_S' or column == 'Chi_square':
        plt.gca().set_ylim(bottom=0)
    plt.show()
R_square
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))

K_S
Chi_square
In [94]:
fig = plt.figure(figsize=(4.2,2.4))
ax1 = fig.add_subplot(1,2,1) 
plot_2d_prob_density(X, Y, kde_Z, ax=ax1,
                     xlabel='x'+speed_unit_text, ylabel='y'+speed_unit_text, colorbar=False)
ax1.grid(False)
ax2 = fig.add_subplot(1,2,2) 
plot_2d_prob_density(X, Y, pdf_Z, ax=ax2,
                     xlabel='x'+speed_unit_text, ylabel='y'+speed_unit_text, colorbar=False)
ax2.grid(False)
ax2.get_yaxis().set_visible(False)
In [ ]:
for fig in [fig_hist, fig_kde, fig_em, fig_gmm]:
    display(fig)
for fig in [fig_time_variability_3d, fig_time_variability_cdf, fig_time_variability_weibull, 
            fig_adjecent_variability_3d, fig_adjecent_variability_cdf, fig_adjecent_variability_weibull,]:
    display(fig)
In [ ]:
import time
save_notebook()
time.sleep(3)
location_name = get_location_name(file_path)
print(location_name)
current_file = 'GMM.ipynb'
output_file = './output_HTML/'+location_name+'.html' 

output_HTML(current_file, output_file)